package com.doit.day02;

import com.alibaba.fastjson.JSON;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.roaringbitmap.RoaringBitmap;
import redis.clients.jedis.Jedis;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

public class _04_消费者算uv2 {
    public static void main(String[] args) {

        //搞一个redis的对象
        Jedis jedis = new Jedis("linux01", 6379);


        //开启线程任务
        new Thread(new RedisBitMapTask(jedis)).start();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("截止到现在的uv数:"+ jedis.pfcount("abc")+",当前时间是："+System.currentTimeMillis());
            }
        },1000,5000);

    }
}

class RedisBitMapTask implements Runnable{
    private Jedis jedis;
    private KafkaConsumer<String, String> consumer;

    public RedisBitMapTask(Jedis jedis){
        Properties props = new Properties();
        //必配项
        props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"linux01:9092");
        props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"group04");
        props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
        props.setProperty(ConsumerConfig.ALLOW_AUTO_CREATE_TOPICS_CONFIG,"true");
        props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");
        props.setProperty(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,"10000");
        //创建消费者对象
        consumer = new KafkaConsumer<String, String>(props);
        this.jedis = jedis;
    }

    @Override
    public void run() {
        //订阅主题
        consumer.subscribe(Arrays.asList("event-log"));
        //拉取数据
        while (true){
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(Integer.MAX_VALUE));
            for (ConsumerRecord<String, String> record : records) {
                String jsonStr = record.value();
                //json串转换成对象
                EventLog eventLog = JSON.parseObject(jsonStr, EventLog.class);
                int guid = eventLog.getGuid();
                //标注
                jedis.pfadd("abc",guid+"");
            }
        }
    }
}
